<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<#include "../../base/_meta.html"> 
<@head>
<script type="text/javascript">
	var eee;
	var dialog = frameElement.dialog;
	$(function() {		
		$.metadata.setType("attr", "validate");
        var v = $("form").validate({
            debug: true
        });
        $("#navtab").ligerTab({onAfterSelectTabItem:f_onTabSelect});
        var items=[{ text: '<font color="red">增加或编辑字段信息后，请【保存到库】</font>'},// 红色字体
        		   {text: '增加',click:addRow, icon: 'add' },
                   { text: '删除', click:delRow, icon: 'delete' },
        		   { line: true },
        		   { text: '保存到库', click:doApply,icon: 'save' }];
        var items2=[{text: '增加',click:addRelation, icon: 'add' },
                   { text: '删除', click:delRelation, icon: 'delete' }]; 
        window['g'] = $("#maingrid").ligerGrid({
            columns: [
            { display: '字段名', name: 'fieldid', align: 'left', width: 80, editor: { type: 'text'}},
            { display: '显示名', name: 'fieldname',align: 'left',  width: 80, editor: { type: 'text' } },
            { display: '类型', name: 'fieldtype', width: 60,
            	editor: { type: 'select', data: fieldtypeData, valueField: 'fieldtype'}, 
            	render: function (item){                    
                    return item.fieldtype;
                }
            }, 
            { display: '长度', name: 'fieldlength', type: 'int', width: 40,editor: { type: 'int'} }, 
            { display: '默认值', name: 'defaultvalue', width: 50,editor: { type: 'int'} }, 
            { display: '必须', name: 'ismust', width: 40,
                editor: { type: 'select', data: ismustData, valueField: 'ismust' },
                render: function (item){
                    if (parseInt(item.ismust) == 1) return '是';
                    return '否';
                }
			}, 
            { display: '主键', name: 'iskey', width: 40, editor: { type: 'select', data: iskeyData, valueField: 'iskey' },
                render: function (item){
                    if (parseInt(item.iskey) == 1) return '是';
                    return '否';
                } },
            { display: '备注', name: 'remark', minWidth: 60, width: 112,editor: { type: 'text' }},
            {display: '表ID', name: 'tableid', width: 0,hide:"hide"}
            ],  pageSize:30,
            url: '/ddesign/field/pagenate?tableid='+ "${(tbl.tableid)!}", 
            enabledEdit: true,
            width: '510',height:'385px',
            onBeforeSubmitEdit: f_onBeforeSubmitEdit,
            toolbar: { items: items}
        	});
        window['g2'] = $("#relationgrid").ligerGrid({
            columns: [{ display: '关系ID', name: 'relationid',hide:true}, 
			{ display: '关系表名', name: 'rtablelname', width: 200}, 
            { display: '本表字段', name: 'lfname', align: 'left', width: 150},
            { display: '关系字段', name: 'rfname',align: 'left',  width: 150}                     
            ],  pageSize:30,
            url: '/ddesign/table/relation?tableid='+ "${(tbl.tableid)!}", 
            width: '500',height:'385px',
            toolbar: { items: items2}
        	});
        $("#chk1").change(function () { 
			refreshSql(); 
		 });
        $("form").ligerForm();
	});
	// 刷新SQL语句
	function f_onTabSelect(targettabid){
		if(targettabid == "sqls"){
			refreshSql();
		}
	}
	// 添加关系表
	function addRelation(){
		var tableid = $("#tableid").val();
		var url="/ddesign/table/g2editrelation?tableid="+tableid;
		$.ligerDialog.open({ url: url, height: 250,width: 500,
			title:'增加表关系'});
	}
	// 删除关系表
	function delRelation(){
		var sRow = g2.getSelectedRows();
		if(sRow.length == 0){
			$.ligerDialog.warn('请至少选择一行进行删除。');
		}else{
			var keys="";
			for(var i=0;i<sRow.length;i++){
				keys += sRow[i].relationid+",";
			}		
			keys =keys.substring(0,keys.length-1);// remove last ',' 
			$.ligerDialog.confirm('您确定要删除选择的【'+sRow.length+'】条数据吗？', function (yes) { 
				if(yes){
					$.ajax({
						url:"/ddesign/table/deleteRelation?keys="+keys,
						success:function(msg){
				        	if(msg >= 1){
				        		var manager = $("#relationgrid").ligerGetGridManager();
								manager.deleteSelectedRow();
				        	}else{
				        		$.ligerDialog.error('删除数据失败。') 
				        	}
				    	}
					});
				}
			});		
		}
	}
	//限制同名字段出现
    function f_onBeforeSubmitEdit(e){ 
		var data = g.getData();
		$("#fieldsave").text("数据修改。");
        if (e.column.name == "fieldid"){// 列名不允许重复
        	var newid = e.value; 
            for(var i=0;i<data.length;i++){
            	if(newid == data[i].fieldid && e.rowindex != i){
            		$.ligerDialog.warn("字段名重复。");
            		return false;
            	}
            } 
        }else if (e.column.name == "fieldname"){// 列名不允许重复
        	var newname = e.value;
        	for(var i=0;i<data.length;i++){
        		if(newname == data[i].fieldname && e.rowindex != i){
        			$.ligerDialog.warn("显示名重复。");
            		return false;
            	}
            } 
        }else if(e.column.name == "fieldlength"){
        	var len = e.value;
        	if(nolenField.indexOf("[" + data[e.rowindex].fieldtype+"]") >= 0){// 没有长度的字段
        		g.updateCell('fieldlength',"",e.rowindex);        		
        	}else{        		
        		if(len <= 0 || len == ""){
        			g.updateCell('fieldlength',"1",e.rowindex);        			
        		}
        	}
        }else if(e.column.name == "fieldtype"){
        	var type = e.value;
        	if(nolenField.indexOf("[" + type +"]") >= 0){// 没有长度的字段
        		g.updateCell('fieldlength',"",e.rowindex);
        	}
        }
        return true;
    }
	// 增加行
	function addRow(){
		var tableid=$("#tableid").val();
		$("#fieldsave").text("添加行。");
    	if(tableid == ""){
    		$.ligerDialog.warn('请先保存表基本信息后，再进行行添加。');
    		return; 
    	}
		var manager = $("#maingrid").ligerGetGridManager();
        manager.addRow({
        	fieldid : "new field",
        	fieldname: "新字段",
        	fieldtype: 'varchar',
        	fieldlength:0,
        	defaultvalue :0 ,
        	ismust : 0,
        	iskey: 0,
        	remark : "空",
        	tableid : $("#tableid").val()
        });
	}
	// 删除行
	function delRow(){
		var sRow = g.getSelectedRows();
		if(sRow.length == 0){
			$.ligerDialog.warn('请至少选择一行进行删除。');
		}else{
			var keys="";
			for(var i=0;i<sRow.length;i++){
				keys += sRow[i].fieldid+",";
			}		
			keys =keys.substring(0,keys.length-1);// remove last ',' 
			$.ligerDialog.confirm('您确定要删除选择的【'+sRow.length+'】条数据吗？', function (yes) { 
				if(yes){
					$.ajax({
						url:"/ddesign/filed/delete?keys="+keys,
						success:function(msg){
				        	if(msg >= 1){
				        		var manager = $("#maingrid").ligerGetGridManager();
								manager.deleteSelectedRow();
				        	}else{
				        		$.ligerDialog.error('删除数据失败。') 
				        	}
				    	}
					});
				}
			});		
		}
	}
	
	// 保存更新
	function doUpdate(){
		var manager = $("#maingrid").ligerGetGridManager();
        var dataEdit = manager.getUpdated();
        $.ajax({
			url:"/ddesign/field/saveUpdate",
			datatype:"json",
			async:false,
			contentType: 'application/json',
			data:"dataEdit=" + JSON.stringify(dataEdit),
			success:function(msg){
	        	if(msg != "1"){
	        		$.ligerDialog.error(msg); 
	        	}else{
	        		$("#fieldsave").text("保存到库成功。");
	        	}
	    	}
		});	
    }
   	// 保存添加
    function doAdd(){   		
    	var manager = $("#maingrid").ligerGetGridManager();
    	var dataAdd = manager.getAdded();    	
		if(dataAdd.length > 0){// 有增加数据
        	$.ajax({
    			url:"/ddesign/field/saveAdd",
    			datatype:"json",
    			async:false,
    			contentType: 'application/json',
    			data:"dataAdd=" + JSON.stringify(dataAdd),
    			success:function(msg){
    	        	if(msg != "1"){
    	        		$.ligerDialog.error(msg); 
    	        	}else{
    	        		$("#fieldsave").text("保存到库成功。");
    	        	}
    	    	}
    		});	
        }
    }
	// 保存到库
	function doApply(){
		doUpdate();
		doAdd();
		g.reload();
	}
	// 刷新SQL
	function refreshSql(){
		var sql = createSql($("#tablepname").val(),g.getData());
		$("#sqls").val(sql);
	}
	// Save
	function doSave(){
		$("#savemsg").text("");
		var form = liger.get('form_edit');
        if (!form.valid()) {
       		return;
        }
		$.ajax({
			url:"/ddesign/table/save",
			data:$("#form_edit").serialize(),
			success:function(data){
	        	if(data.tableid != ""){
	        		parent.window.relaodTree();// Rfresh grid of users
	        		$("#tableid").val(data.tableid);
	        		$("#savemsg").text("保存成功。");
	        	}else{
	        		$.ligerDialog.error("保存失败，请确认信息无误后重试。"); 
	        	}
	    	},
	    	error: function(XMLHttpRequest, textStatus, errorThrown) {
	    		$.ligerDialog.error("服务器连接失败。"); 
            }
		});	
	}
	// 刷新界面
	function doSearch(){
		g2.reload();
	}
</script>
<style type="text/css">
 body{ font-size:12px;}
 .l-table-edit {}
 .l-table-edit-td{ padding:4px;}
 .l-button-submit,.l-button-test{width:60px; float:center}
 .l-verify-tip{ left:230px; top:120px;}
</style>
</@head>
<body style="overflow-x: hidden; padding: 2px;">
 <form id="form_edit" class="liger-form" data-validate="{}"> 
	<input type="hidden" name="screen" id="screen" value="${(screen)!}"/>
	<input type="hidden" name="projectid" id="projectid" value="${(r.projectcode)!}"/>
	<input type="hidden" name="diagramid" id="diagramid" value="${(r.diagramid)!}"/>
	
	<div id="navtab" style="width: 500px; height:440px;heioverflow:hidden;">
		<div tabid="base" title="基本信息" lselected="true"  style="width: 500px; height:400px;" >
			<table cellpadding="0" cellspacing="0" class="l-table-edit" width="100%" >
				<tr>
					<td align="right" class="l-table-edit-td" >项目名称:</td>
					<td align="left" class="l-table-edit-td" style="width: 160px">
						${(r.projectname)!}
					</td>
					<td align="left"></td>
					<td align="left"></td>
					
				</tr>
				<tr>
					<td align="right" class="l-table-edit-td" >图表名称:</td>
					<td align="left" class="l-table-edit-td" style="width: 160px">
						${(r.diagramname)!}
					</td>
					<td align="left"></td>
					<td align="left"></td>
				</tr>
				<tr>
					<td align="right" class="l-table-edit-td" >英文表名:</td>
					<td align="left" class="l-table-edit-td" style="width: 160px">
					<input
						name="tablepname" type="text" id="tablepname" ltype="text"
						validate="{required:true,minlength:3,maxlength:100}" value="${(tbl.tablepname)!}"/>
					<#if screen == "E">
					<input
						name="tableid" type="hidden" id="tableid" value="${(tbl.tableid)!}"/>
					</#if>
					</td>
					<td align="left"></td>
					<td align="left"></td>
				</tr>
				<tr>
					<td align="right" class="l-table-edit-td" >中文表名:</td>
					<td align="left" class="l-table-edit-td" style="width: 160px">
					<input
						name="tablelname" type="text" id="tablelname" ltype="text"
						validate="{required:true,minlength:3,maxlength:100}" value="${(tbl.tablelname)!}"/>
					</td>
					<td align="left"></td>
					<td align="left"></td>
				</tr>
				
				<tr>
		           <td align="right" class="l-table-edit-td">备注描述:</td>
		           <td align="left" class="l-table-edit-td" colspan="2" > 
		           <textarea name="remark" id="remark" cols="40" rows="13" 
		           			class="l-textarea"  style="width:400px">${(tbl.remark)!}</textarea>
		           </td> <td align="left"></td>
		       </tr>
		       <tr>
					<td align="left" class="l-table-edit-td" >&nbsp;</td>
					<td align="left" class="l-table-edit-td" style="width: 160px">
					<span id="savemsg" style="color:green"></span>
					</td>
					<td align="left"></td>
					<td align="left"></td>
				</tr>
				<tr>
				     <td align="center" colspan="4" width="500">
					<input type="button" value="保存" class="l-button l-button-test" onclick="doSave();"/>
				   </td>
		      </tr>
			</table>
		</div>
		<div tabid="fields" title="字段信息" style="width: 545px; height:410px;">
			<div id="maingrid" style="margin:0; padding:0"></div>
			<span id="fieldsave" style="color:green"></span>
		</div>
		<div tabid="sqls" title="SQL语句">
		<table cellpadding="0" cellspacing="0" class="l-table-edit" width="100%" >
			<tr>
	           <td align="right" class="l-table-edit-td"><input type="checkbox" name="chbox" id="chk1" /></td>
	           <td align="left" class="l-table-edit-td" colspan="2" > 
	         	 表已经存在
	           </td> 
	           <td align="left">&nbsp;</td>
		    </tr>
			<tr>
	           <td align="right" class="l-table-edit-td">建表SQL:</td>
	           <td align="left" class="l-table-edit-td" colspan="2" > 
	           <textarea name="sqls" id="sqls" cols="42" rows="22" 
	           			class="l-textarea"  style="width:420px"></textarea>
	           </td><td align="left"></td>
		    </tr>
		</table>
		</div>
		<div tabid="relations" title="关系表">
			<div id="relationgrid" style="margin:0; padding:0"></div>
			<span id="relationsave" style="color:green"></span>
		</div>
</div>
</form>
<script type="text/javascript">
// if has radio,select,checkbox,put here for init
</script>
</body>
</html>